package cn.virens.common.simple;

import cn.hutool.core.util.StrUtil;
import cn.virens.common.exception.APIException;
import cn.virens.common.utils.Assert;
import io.mybatis.provider.EntityTable;
import io.mybatis.provider.EntityTableFactory;

import java.util.function.Supplier;

public class DynamicTableNameFactory implements EntityTableFactory {
    private static DynamicTableNameLocal local = new DynamicTableNameLocal();

    @Override
    public EntityTable createEntityTable(Class<?> entityClass, Chain chain) {
        EntityTable r = chain.createEntityTable(entityClass);
        if (r != null && StrUtil.isNotEmpty(r.table())) {
            r.table(local.generateDynamic(r));
        }

        return r;
    }

    /**
     * 设置动态表名变量(当前线程/子线程有效)
     *
     * @param key      关键词
     * @param supplier 供应者
     */
    public static void variable(String key, Supplier<String> supplier) {
        local.variable(Assert.isEmpty(key), supplier);
    }

    /**
     * 设置动态表名变量(当前线程/子线程有效)
     *
     * @param key   关键词
     * @param value 替换值
     */
    public static void variable(String key, String value) {
        local.variable(Assert.isEmpty(key), value);
    }

    @Override
    public int getOrder() throws APIException {
        return Integer.MAX_VALUE - 10;
    }
}
